const util = {
  // 设置 localStorage item
  setItem: (key, value) => {
    window.localStorage.setItem(key, JSON.stringify(value))
  },
  // 获取 localStorage item
  getItem: (key) => {
    return JSON.parse(window.localStorage.getItem(key))
  },
  // 删除 localStorage item
  removeItem: (key) => {
    window.localStorage.removeItem(key)
  },
  // 设置cookie
  setCookie (name, value, hours) {
    let cookie = `${name}=${value}`
    if (hours > 0) {
      const d = new Date()
      d.setTime(d.getTime() + hours * 3600000)
      cookie += `;expires=${d.toGMTString()}`
    }
    document.cookie = cookie
    console.warn(document.cookie)
  },
  // 获取cookie
  getCookie (name) {
    let search = `${name}=` // 查询检索的值
    let returnvalue = '' // 返回值
    if (document.cookie.length > 0) {
      let sd = document.cookie.indexOf(search)
      if (sd !== -1) {
        sd += search.length
        let end = document.cookie.indexOf(';', sd)
        if (end === -1) {
          end = document.cookie.length
        }
        // unescape() 函数可对通过 escape() 编码的字符串进行解码。
        returnvalue = unescape(document.cookie.substring(sd, end))
      }
    }
    return returnvalue
  },
  // 清除cookie
  clearCookie () {
    this.setCookie('username', '', -1)
  },
  // 数组去重
  unique: (arr) => {
    let newArr = []
    arr.map((item) => {
      if (item !== '') {
        newArr.push(item)
      }
    })
    return [...(new Set(newArr))]
  },
  // 去重操作
  uniqeByKeys: (array, keys) => {
    const arr = []
    const hash = {}
    for (let i = 0, j = array.length; i < j; i++) {
      let k = obj2Key(array[i], keys)
      if (!(k in hash)) {
        hash[k] = true
        arr.push(array[i])
      }
    }
    return arr
  },
  // 设置表格滚动到底部的事件
  tableScrollBottom (selector, callback) {
    const dom = document.querySelector(selector)
    dom.onscroll = async () => {
      let scrollPos = dom.scrollTop // 滚动条距顶部距离(页面超出窗口的高度)
      let scrollHei = dom.scrollHeight
      let divHei = dom.offsetHeight
      if (Math.ceil(scrollPos) + divHei >= scrollHei) {
        callback()
      }
    }
  }

}

// 将对象元素转换成字符串以作比较
function obj2Key (obj, keys) {
  let n = keys.length
  const key = []
  while (n--) {
    key.push(obj[keys[n]])
  }
  return key.join('|')
}

export default util
